<template lang="pug">
  div.cpt-tree-node.relative()
    div.handler
      span.icon.icon-spander(:class="[icon]" @click="toggleHandler(nodeData)")
      Checkbox(:value="nodeData.selected" :indeterminate="getIndeterminate()" @click.native.prevent="selectHandler(nodeData)")
      span.text {{nodeData.title}}
    cpt-tree-node(v-if="hasChildren" v-show="nodeData.open" :key="item"  v-for="item in nodeData.children" @on-change="selectHandler" @on-toggle="toggleHandler(item)"  :nodeData="item")
</template>

<script>
import _ from 'lodash';
export default {
  name: 'CptTreeNode',
  props: {
    nodeData: {
      type: Object,
      default: null
    },
    level: {
      type: Number,
      default() {
        return 0;
      }
    }
  },
  computed: {
    hasChildren() {
      return this.nodeData.children && this.nodeData.children.length;
    },
    icon() {
      if (this.hasChildren) {
        return this.nodeData.open ? 'icon-down-dir' : 'icon-right-dir';
      }
    }
  },
  methods: {
    getIndeterminate() {
      const selectedChildren = _.filter(this.nodeData.children, child => {
        return child.selected;
      });
      return (
        selectedChildren.length > 0 &&
        selectedChildren.length < this.nodeData.children.length
      );
    },
    selectHandler(nodeData) {
      this.$emit('on-change', nodeData);
    },
    toggleHandler(nodeData) {
      this.$emit('on-toggle', nodeData);
    }
  }
};
</script>
